package com.lanhao.aot.afterselling;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.Key;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * 开放接口加解密签名工具箱
 * =================================================================================
 *
 * =================================================================================
 */
public class WitSecUtil {
    private static final Logger logger = LoggerFactory.getLogger(WitSecUtil.class);
    
    private static final String AES_TYPE = "AES/ECB/PKCS5Padding";
    //--------------------------------------------------------------------------------------------------------------

    /**
     * 加密
     * 
     * @param aesKey    加密KEY
     * @param plainText 待加密字符串
     * @return 加密结果
     */
    public static String encrypt(String aesKey, String plainText) {
        if (StringUtils.isBlank(plainText)) {
            return "";
        }
        
        byte[] encrypt = null;
        try {
            Key key = new SecretKeySpec(aesKey.getBytes(), "AES");;
            Cipher cipher = Cipher.getInstance(AES_TYPE);
            cipher.init(Cipher.ENCRYPT_MODE, key);
            encrypt = cipher.doFinal(plainText.getBytes("UTF-8"));
            
            return new String(Base64.encodeBase64(encrypt), "UTF-8");
        } catch (Throwable e) {
            logger.error("加密失败", e);
        }
        return "加密失败";
    }

    /**
     * 解密
     * 
     * @param aesKey      解密KEY
     * @param encryptData 加密的字符串
     * @return 解密结果
     */
    public static String decrypt(String aesKey, String encryptData) {
        if (StringUtils.isBlank(encryptData)) {
            return "";
        }
        
        byte[] decrypt = null;
        try {
            Key key = new SecretKeySpec(aesKey.getBytes(), "AES");;
            Cipher cipher = Cipher.getInstance(AES_TYPE);
            cipher.init(Cipher.DECRYPT_MODE, key);
            decrypt = cipher.doFinal(Base64.decodeBase64(encryptData));
            
            return new String(decrypt, "UTF-8").trim();
        } catch (Throwable e) {
            logger.error("解密失败", e);
        }
        return "解密失败";
    }
    
    //--------------------------------------------------------------------------------------------------------------
    
    /**
     * 生成签名
     * 
     * @param allParams 待签名参数
     * @param appSec    签名密钥
     * @return 签名
     */
    public static String genSign(Map<String, ?> allParams, String appSec) {
        return genSign(allParams, Collections.emptyList(), appSec);
    }

    /**
     * 对allParams进行签名，其中ignoreParamNames这些参数不参与签名
     * @param allParams 待签名参数
     * @param ignoreParamNames 需要忽略的参数
     * @param appSec 签名密钥
     * @return 签名
     */
    public static String genSign(Map<String, ?> allParams, List<String> ignoreParamNames, String appSec) {
        try {
            List<String> paramNames = new ArrayList<>(allParams.size());
            paramNames.addAll(allParams.keySet());
            if (paramNames.contains("sign")) { // 跳过sign参数
                paramNames.remove("sign");
            }
            if(ignoreParamNames != null && ignoreParamNames.size() > 0){
                for (String ignoreParamName : ignoreParamNames) {
                    paramNames.remove(ignoreParamName);
                }
            }
            Collections.sort(paramNames);

            StringBuilder sb = new StringBuilder();
            sb.append(appSec);
            for (String paramName : paramNames) {
                sb.append(paramName).append(allParams.get(paramName));
            }
            sb.append(appSec);

            return WitSecUtil.getSha1Sign(sb.toString());
        } catch (Throwable e) {
            throw new RuntimeException(e);
        }
    }

    //-----------------------------------------------------------------------------------------------------------------
    
    /**
     * 生成SHA1格式签名
     *
     * @param planText 代签名字符串
     * @return SHA1格式签名
     */
    public static String getSha1Sign(String planText) {
        try {
            return byte2hex(getSHA1Digest(planText));
        } catch (Throwable e) {
            return "签名失败";
        }
    }
    /**
     * 取得字符串的SHA1编码字节数组
     *
     * @param data
     * @return
     * @throws IOException
     */
    public static byte[] getSHA1Digest(String data) throws IOException {
        byte[] bytes = null;
        try {
            MessageDigest md = MessageDigest.getInstance("SHA-1");
            bytes = md.digest(data.getBytes("UTF-8"));
        } catch (GeneralSecurityException gse) {
            throw new IOException(gse);
        }
        return bytes;
    }
    
    /**
     * 二行制转字符串
     */
    public static String byte2hex(byte[] b) {
        return byte2hex(b, true);
    }

    /**
     * 二行制转字符串
     * @param b
     * @param toUpperCase 是否转化为大写
     * @return
     */
    public static String byte2hex(byte[] b, boolean toUpperCase) {
        StringBuffer hs = new StringBuffer();
        String stmp = "";
        for (int n = 0; n < b.length; n++) {
            stmp = (Integer.toHexString(b[n] & 0XFF));
            if (stmp.length() == 1)
                hs.append("0").append(stmp);
            else
                hs.append(stmp);
        }

        if (toUpperCase) {
            return hs.toString().toUpperCase();
        }
        return hs.toString();
    }
    
    //-----------------------------------------------------------------------------------------------------------------
}
